package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.utils.CommonAdTools
import com.wanban.adutils.utils.VideoInterstitialAdTools
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.db.entity.NoteModel
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.NoteExportEntity
import com.juku2024.juku.dialog.CommonDialog
import com.juku2024.juku.dialog.DialogUtils
import com.juku2024.juku.dialog.NoteRewardAdDialog
import com.juku2024.juku.tools.AlertUtils
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.RxUtils
import com.juku2024.juku.viewmodel.VideoDetailViewModelNew
import com.juku2024.juku.widget.LoadingView
import java.io.File

class NoteDetailActivity : AppCompatActivity() {

    private lateinit var etTitle: EditText
    private lateinit var etContent: EditText
    private lateinit var btnSave: TextView
    private lateinit var btnBack: ViewGroup
    private lateinit var btnExport: TextView
    private lateinit var loadingView: LoadingView
    private lateinit var bannerRoot: FrameLayout

    private var id: Long = -1
    private var currentNote: NoteModel? = null
    private var exportDialog : CommonDialog? = null
    private var downloadAdDialog: NoteRewardAdDialog? = null
    private val downloadAdTools by lazy { CommonAdTools() }
    // 数据控制器
    private val viewModel by lazy { getViewModel(VideoDetailViewModelNew::class.java) }
    /**
     * 获取ViewModel
     */
    fun <T : ViewModel> getViewModel(modelClass: Class<T>): T {
        return ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )[modelClass]
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 根据设置来改编状态栏颜色
        AppUtils.setAppStyle(this)
        setContentView(R.layout.activity_note_detail)
        initView()
        bindEvent()
        initData()
        loadBanner()
    }


    private fun initView() {
        etTitle = findViewById(R.id.etTitle)
        etContent = findViewById(R.id.etContent)
        btnBack = findViewById(R.id.btnBack)
        btnSave = findViewById(R.id.tvSave)
        loadingView = findViewById(R.id.detail_loadingView)
        bannerRoot = findViewById(R.id.bannerRoot)
        btnExport = findViewById(R.id.tv_export)
        downloadAdDialog = NoteRewardAdDialog(this)
    }

    private fun bindEvent() {
        btnBack.setOnClickListener {
            finish()
        }

        btnSave.setOnClickListener {
            val title = etTitle.text?.toString()
            if (TextUtils.isEmpty(title)) {
                Toast.makeText(this, "请输入笔记标题！", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            val content = etContent.text?.toString()
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(this, "请输入笔记内容！", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }


            val note = NoteModel()
            if (id >= 0) {
                note.id = id
            }
            note.date = System.currentTimeMillis()
            note.title = title
            note.content = content
            NoteRoomUtils.getInstance().noteDao().insert(note)

            Toast.makeText(this, "保存成功！", Toast.LENGTH_LONG).show()

            finish()
        }

        btnExport.setOnClickListener {
//            val rewardAd = AdRoomUtils.getInstance().adDao().query(AdConstants.AD_ID_DOWNLOAD_REWARD_AD)?.adInfo?.firstOrNull()
//            if (rewardAd == null) {
//                // 导出笔记
//                exportNote()
//                return@setOnClickListener
//            }
            downloadAdDialog?.onShowAdListener = object : OnNoDoubleClickListener {
                override fun onNoDoubleClick(v: View?) {
                    super.onNoDoubleClick(v)
                    downloadAdDialog?.dismiss()
                    loadingView.showLoading()
                    viewModel.loadMultipleAd(
                        this@NoteDetailActivity,
                        VideoDetailViewModelNew.AD_TYPE_DOWNLOAD
                    ) {
                        loadingView.hideLoading()
                        // 导出笔记
                        exportNote()
                    }
                }
            }
            downloadAdDialog?.show()
        }
    }

    private fun initData() {
        id = intent?.getLongExtra("id", -1) ?: -1
        if (id >= 0) { // 只有新创建才会加载广告
            loadingView.showLoading()
            VideoInterstitialAdTools.loadAd(this, object : OnLoadAdCallback() {

                override fun onAdComplete() {
                    super.onAdComplete()
                    if (isFinishing) return
                    loadingView.hideLoading()

                    val note = NoteRoomUtils.getInstance().noteDao().query(id) ?: return
                    etTitle.setText(note.title)
                    etContent.setText(note.content)
                    currentNote = note
                    etTitle.post {
                        etTitle.requestFocus()
                    }
                }

                override fun onAdLoadFailed(errorCode: Int) {
                    super.onAdLoadFailed(errorCode)
                    if (isFinishing) return
                    loadingView.hideLoading()

                    val note = NoteRoomUtils.getInstance().noteDao().query(id) ?: return
                    etTitle.setText(note.title)
                    etContent.setText(note.content)
                    currentNote = note
                    etTitle.post {
                        etTitle.requestFocus()
                    }
                }

                override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                    super.onAdLoaded(ad, *tag)
                    if (isFinishing) return
                    loadingView.hideLoading()
                    RxUtils.timer(500) {
                        VideoInterstitialAdTools.showAd(this@NoteDetailActivity)
                    }
                }
            })
        }
    }


    private fun loadBanner(){
        val bannerAdTools = CommonAdTools()
        bannerAdTools.loadAd(this, AdConstants.AD_ID_VIDEO_DETAIL_PAUSE, object: OnLoadAdCallback(){
            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                if (isFinishing) return
                bannerRoot.visibility = View.VISIBLE
                bannerAdTools.showAd(bannerRoot)
            }

            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                if (isFinishing) return
            }
        })
    }

    private fun exportNote() {
        val title = etTitle.text?.toString()
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "请输入笔记标题！", Toast.LENGTH_LONG).show()
            return
        }
        val content = etContent.text?.toString()
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "请输入笔记内容！", Toast.LENGTH_LONG).show()
            return
        }

        if (exportDialog == null) {
            exportDialog = DialogUtils.showCommonDialog(
                this,
                "您确定要导出当前当前记录吗？",
                getString(R.string.confirm), {
                    exportDialog?.dismiss()
                    RxUtils.doObservable({
                        val fileDir = File(externalMediaDirs.first(), "note")
                        if (!fileDir.exists()) {
                            fileDir.mkdirs()
                        }
                        val filePath = fileDir.absolutePath + File.separator + "note_${System.currentTimeMillis()}.txt"
                        val file = File(filePath)
                        file.createNewFile()
                        file.appendText("标题：$title")
                        file.appendText("\n")
                        file.appendText("笔记：$content")
                        if (it.isDisposed) return@doObservable
                        it.onNext(file.absolutePath)
                    }, { path ->
                        val noteExportEntity = NoteExportEntity()
                        noteExportEntity.title = title
                        noteExportEntity.data = currentNote?.date?:System.currentTimeMillis()
                        noteExportEntity.content = content
                        noteExportEntity.path = path
                        NoteRoomUtils.getInstance().noteExportDao().insert(noteExportEntity)
                        AlertUtils.alert("当前笔记已导出！")
                    })

                },
                getString(R.string.cancel), {
                    exportDialog?.dismiss()
                }
            )
        }
        exportDialog?.show()
    }

    private fun loadDownloadAd(rewardAdId: Long) {
        loadingView.showLoading()
        downloadAdTools.loadAd(this, rewardAdId, object: OnLoadAdCallback(){
            private var isUserEarnedReward = false
            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                if (isFinishing || isDestroyed) return
                downloadAdTools.showAdInActivity(this@NoteDetailActivity)
            }

            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                if (isFinishing || isDestroyed) return
                loadingView.hideLoading()
                exportNote()
            }

            override fun onUserEarnedReward(amount: Int) {
                super.onUserEarnedReward(amount)
                isUserEarnedReward = true
            }

            override fun onAdComplete() {
                super.onAdComplete()
                downloadAdTools.release()
                loadingView.hideLoading()
                exportNote()
            }
        })
    }
}